package com.firmiana.jt809.task.sub;

import com.firmiana.jt809.connection.ConnectionManager;
import com.firmiana.jt809.entity.BizConnection;
import com.firmiana.jt809.service.SubLinkService;
import com.firmiana.jt809.task.ITask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author hucl
 * @date 2020/8/26 14:37
 */
@Service
@Slf4j
public class SubTaskService implements ITask {
    @Resource
    private SubLinkService subLinkService;

    private final AtomicBoolean isTimeStart = new AtomicBoolean();
    private int count;

    @Override
    public boolean start() {
        log.info("======启动【子链路监管心跳服务】定时发送心跳、断线重连线程=======");
        isTimeStart.set(true);
        Thread task = new Thread(this::connectAndHeatBeatTaskThread);
        task.setName("子链路监管线程--");
        task.start();
        return isTimeStart.get();
    }

    private void connectAndHeatBeatTaskThread() {
        while (isTimeStart.get()) {
            ++count;
            try {
                if (count % 20 ==0) {
                    // 30秒给各个从链路发送心跳数据，防止断开
                    ConcurrentMap<String, BizConnection> allSubConnections = ConnectionManager.getAllSubConnections();
                    allSubConnections.forEach((key, subChanel) -> {
                        log.info("从链路发送心跳给：" + key);
                        // 从链路断线重连
                        if (!subChanel.getSubLink().isRunning()) {
                            subChanel.getSubLink().reconnect();
                        }
                        // 发送从链路心跳
                        subLinkService.subLinkHeartBeatRequest(key);
                    });
                }
                if (count == Integer.MAX_VALUE / 2) {
                    count = 1;
                }

                TimeUnit.MINUTES.sleep(1L);
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage(), e);
            }
        }
    }
    @Override
    public void stop() {
        isTimeStart.compareAndSet(true, false);
    }
}
